﻿using System;
using System.Windows.Forms;
using log4net;

namespace BarberShop
{
    public partial class ServiceManagerForm : Form
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof (ServiceManagerForm));

        private readonly MainForm _parentForm;

        public ServiceManagerForm(MainForm parentForm)
        {
            InitializeComponent();
            _parentForm = parentForm;
            servicesDataGridView.DataSource = _parentForm.dbDataSet.Services;
            TryToSelectFirstRow();

            UpdateFormControlsConfiguration();
        }

        private void SaveButtonClick(object sender, EventArgs e)
        {
            Close();
        }

        private void RemoveServiceButtonClick(object sender, EventArgs e)
        {
            _parentForm.DeleteService(GetSelectedServiceId());
            UpdateFormControlsConfiguration();
        }

        private void AddServiceButtonClick(object sender, EventArgs e)
        {
            _parentForm.AddService();
            UpdateFormControlsConfiguration();
        }

        private int GetSelectedServiceId()
        {
            DataGridViewRow selectedRow = servicesDataGridView.CurrentRow;
            return selectedRow != null ? int.Parse(selectedRow.Cells[0].Value.ToString()) : 0;
        }

        private void TryToSelectFirstRow()
        {
            removeServiceButton.Enabled = servicesDataGridView.Rows.Count != 0;
            if (servicesDataGridView.Rows.Count == 0)
            {
                Log.Warn("Unable to select first service, servicesDataGridView.Rows.Count == 0");
                return;
            }

            DataGridViewRow firstRow = servicesDataGridView.Rows[0];
            firstRow.Selected = true;
        }

        private void UpdateFormControlsConfiguration()
        {
            removeServiceButton.Enabled = servicesDataGridView.Rows.Count > 0;
        }

        private void FilterPreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            switch (e.KeyValue)
            {
                case 13: //Enter key
                case 27: //Esc key
                    Close();
                    break;
            }

        }
    }
}